package com.lsj.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.lsj.common.constant.AuthServiceConstant;
import com.lsj.common.exception.BizCodeEnum;
import com.lsj.common.utils.R;
import com.lsj.gulimall.auth.feign.MemberFeignService;
import com.lsj.gulimall.auth.feign.ThirdPartySmsService;
import com.lsj.gulimall.auth.utils.CreateCodeNumUtil;
import com.lsj.gulimall.auth.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import sun.applet.resources.MsgAppletViewer;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**注册Controller
 * @author 梁胜君
 * @version 1.0
 * @create 2022/4/1 17:54
 */
@Controller
@RequestMapping("/reg")
@Slf4j
public class RegisterController {


    @Autowired
    ThirdPartySmsService thirdPartySmsService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 发送短信验证码
     * @return
     */
    @RequestMapping("/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone){

        // 获取redis中的验证码
        String codeRedis = redisTemplate.opsForValue().get(AuthServiceConstant.SMS_CODE_CACHE_PREFIX+phone);
        if (!StringUtils.isEmpty(codeRedis)) {
            // 获取redis缓存验证码的时间
            long setCodeTime = Long.parseLong(codeRedis.split("_")[1]);
            log.info("60秒内不能发送短信{}",setCodeTime);
            if(System.currentTimeMillis() - setCodeTime < 60*1000) {
                // 60秒内不能重新发送短信
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        // 生成验证码
        String code = CreateCodeNumUtil.createCodeNum()+ "_"+ System.currentTimeMillis();
        // 将生成的验证存入redis获取中 k 为sms:code:phone v 为 code
        redisTemplate.opsForValue().set(AuthServiceConstant.SMS_CODE_CACHE_PREFIX+phone,code,10, TimeUnit.MINUTES);
        // 调用第三方短信发送接口
        log.info("生成的短信验证码是{}",code.split("_")[0]);
        //thirdPartySmsService.sendCode(phone,code.split("-")[0]);
        return R.ok();
    }


    /**
     * 注册
     * @param vo
     * @param result
     * @return
     */
    @PostMapping("/register")
    public String register(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            Map<String, String> errors = fieldErrors.stream().collect(Collectors.toMap(fieldError -> {
                return fieldError.getField();
            }, fieldError -> {
                return fieldError.getDefaultMessage();
            }));
            redirectAttributes.addFlashAttribute("errors",errors);
            // 校验出错，转发到注册页面
            return "redirect:http://shengjunauth.com/reg.html";
        }

        // 1、校验验证码是否正确
        String code = vo.getCode();
        String redisCode = redisTemplate.opsForValue().get(AuthServiceConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(redisCode)) {
            if (code.equals(redisCode.split("_")[0])) {
                // 验证码通过，调用远程服务进行注册
                R r = memberFeignService.register(vo);
                if (r.getCode() == 0) {
                    // 删除验证码
                    redisTemplate.delete(AuthServiceConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                    // 远程服务调用成功，注册完成后跳转到登录页面
                    return "redirect:http://shengjunauth.com/login.html";

                } else {
                    // 远程服务调用发生错误，返回注册页面并提示错误信息
                    HashMap<String, String> errors = new HashMap<>();
                    errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://shengjunauth.com/reg.html";
                }
            } else {
                HashMap<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://shengjunauth.com/reg.html";
            }
        } else {
            HashMap<String, String> errors = new HashMap<>();
            errors.put("code","验证码超时，请重新获取验证码");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://shengjunauth.com/reg.html";
        }
    }
}
